package com.taichuan.selfcheck.ui.fragment;


import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import com.taichuan.selfcheck.R;
import com.taichuan.selfcheck.config.PropertyDefaultValue;
import com.taichuan.selfcheck.eventbus.ReadSenseTemperatureValueEvent;
import com.taichuan.selfcheck.eventbus.TempEvent;
import com.taichuan.selfcheck.eventbus.TempFragmentOpenEvent;
import com.taichuan.selfcheck.hardware.DeviceUtils;
import com.taichuan.selfcheck.mvp.presenter.EmptyPresenter;
import com.taichuan.selfcheck.mvp.viewinterface.EmptyInterface;
import com.taichuan.selfcheck.ui.dialog.ResultDialog;
import com.taichuan.selfcheck.ui.fragment.base.AppBaseFragment;
import com.taichuan.serialcommunication.SerialPortPublic;
import com.taichuan.tcutils.taichuan.SystemUtils;
import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import butterknife.BindView;
import butterknife.OnClick;

/**
 * 温度测试
 */
public class TempTestFragment extends AppBaseFragment<EmptyInterface, EmptyPresenter> implements EmptyInterface {

    @BindView(R.id.temperatureTv)
    TextView mTempValue;
    @BindView(R.id.temp_control_button)
    Button tempControlBtn;

    private final static int MSG_REFRESH_TEMP_VALUE = 1;
    private final static int MSG_START_TEMP_QUERY = 2;

    //测试结果对话框
    private ResultDialog resultDialog;

    @Override
    protected boolean isAllowAutoFinishFragment() {
        return false;
    }

    @Override
    public void doOnAutoFinishFragment() {
        resultDialog.show();
    }

    @Override
    protected void getBundleValues(Bundle bundle) {

    }

    private Handler mHandler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message message) {
            switch (message.what) {
                case MSG_REFRESH_TEMP_VALUE: {
                    if (mTempValue != null) {
                        double temperature = Double.parseDouble((String) message.obj);
                        if (!SystemUtils.isVankeSiteBoxDevice()){           //测温门禁设备
                            if (PropertyDefaultValue.TEMPERATURE_MAX < temperature) {
                                mTempValue.setText("体温异常：" + temperature + "℃");
                                mTempValue.setBackgroundResource(R.drawable.shape_temperature_error);
                            } else {
                                mTempValue.setText("体温探测：" + temperature + "℃");
                                mTempValue.setBackgroundResource(R.drawable.shape_temperature_nor);
                            }
                        }else {
                            mTempValue.setText("温感温度：" + temperature + "℃");
                            mTempValue.setBackgroundResource(R.drawable.shape_temperature_nor);
                        }
                    }
                    break;
                }
                case MSG_START_TEMP_QUERY:{
                    if (SystemUtils.isVankeSiteBoxDevice()){
                        //主动查询温感温度
                        SerialPortPublic.getTemp();
                        //延时1秒后再次执行
                        mHandler.sendEmptyMessageDelayed(MSG_START_TEMP_QUERY,1 * 1000);
                    }

                    break;
                }
            }

            return false;
        }
    });

    private void startQueryTemp(){
        if (SystemUtils.isVankeSiteBoxDevice()){
            //移除Handler事件
            mHandler.removeMessages(MSG_START_TEMP_QUERY);
            mHandler.sendEmptyMessage(MSG_START_TEMP_QUERY);
        }
    }

    @Override
    public boolean dispatchKeyEvent(KeyEvent event) {
        if (resultDialog.isShowing()) {
            resultDialog.dispatchKeyEvent(event);
        }
        return super.dispatchKeyEvent(event);
    }

    @Override
    protected int setContentViewId() {
        return R.layout.fragment_temp;
    }

    @Override
    protected void initView(View view, Bundle bundle) {
        EventBus.getDefault().register(this);

        if (SystemUtils.isTC5000D_XL5_4G_WIFI_TempBoard()) {
            tempControlBtn.setVisibility(View.VISIBLE);
            tempControlBtn.setTag("close");
        } else {
            tempControlBtn.setVisibility(View.GONE);
        }

        //万科智慧工地设备 开启主动查询温度
        startQueryTemp();

        //通知页面开启
        EventBus.getDefault().post(new TempFragmentOpenEvent(true));
        resultDialog = new ResultDialog(PropertyDefaultValue.FUNCTION_TEST_14, getResources().getString(R.string.temp_test), mActivity);       //设置弹窗发送的事件——温度测试
    }

    @OnClick({R.id.temp_control_button})
    @Override
    protected void onXmlClick(View v) {
        super.onXmlClick(v);
        switch (v.getId()) {
            case R.id.temp_control_button: {
                if (SystemUtils.isTC5000D_XL5_4G_WIFI_TempBoard()) {
                    if (tempControlBtn.getTag().equals("close")) {
                        tempControlBtn.setTag("open");
                        tempControlBtn.setText(getStrById(R.string.open_temp_module));
                        DeviceUtils.openOrCloseXL5Temp(false);
                        showMsg("【关闭】矩阵测温模块电源 成功！");
                    } else {
                        tempControlBtn.setTag("close");
                        tempControlBtn.setText(getStrById(R.string.close_temp_module));
                        DeviceUtils.openOrCloseXL5Temp(true);
                        showMsg("【开启】矩阵测温模块电源 成功！");
                    }
                }
                break;
            }
        }
    }

    @Subscribe
    public void onEvent(TempEvent tempEvent) {
        if (!SystemUtils.isTC5000D_XL5_4G_WIFI_TempBoard()) {
            int temp = tempEvent.getTempValue();
            String it = (Integer) (temp / 10) + "";
            String de = (Integer) (temp % 10) + "";
            String result = String.format("%s.%s", it, de);
            mHandler.sendMessage(mHandler.obtainMessage(MSG_REFRESH_TEMP_VALUE, result));
        }
    }

    @Subscribe
    public void onReadSenseTemperatureEvent(ReadSenseTemperatureValueEvent event) {
        if (SystemUtils.isTC5000D_XL5_4G_WIFI_TempBoard()) {
            mHandler.sendMessage(mHandler.obtainMessage(MSG_REFRESH_TEMP_VALUE, event.getIntTempValue() + ""));
        }
    }

    @Override
    protected EmptyPresenter createPresenter() {
        return new EmptyPresenter();
    }

    @Override
    public void showLoading() {

    }

    @Override
    public void hideLoading() {

    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        //通知页面关闭
        EventBus.getDefault().post(new TempFragmentOpenEvent(false));
        //移除所有Handler事件
        mHandler.removeCallbacksAndMessages(null);

        EventBus.getDefault().unregister(this);
    }
}
